package com.invengo.library_rfid.analyze.utils.uhf.formatHelp;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class CReaderEpcCode2 {
    public long m_ulLogout = 0;
    private long m_ulEmpty = 0;
    private long m_ulCardIDHeader = 0;
    public long m_ulLibCode = 0;
    public long m_ulLibTagType = 3;
    public long m_ulCardID = 0;
    public long m_ulRemain = 0;

    public CReaderEpcCode2() {
    }

    public CReaderEpcCode2(byte[] byData) throws Exception {
        if (byData.length != 12) {
            throw new Exception("CReaderEpcCode2 data length must be 12 bytes");
        }
        BitClass bitClass = new BitClass(byData);
        m_ulLogout = bitClass.getValueUL(0, 4);
        m_ulEmpty = bitClass.getValueUL(4, 6);
        m_ulCardIDHeader = bitClass.getValueUL(10, 20);
        m_ulLibCode = bitClass.getValueUL(30, 16);
        m_ulLibTagType = bitClass.getValueUL(46, 4);
        m_ulCardID = (m_ulCardIDHeader << 44) + bitClass.getValueUL(50, 44);
        m_ulRemain = bitClass.getValueUL(94, 2);
    }

    public int getBytes(byte[] byResult) throws Exception {
        try {
            BitClass tmpClass = new BitClass();
            tmpClass.addBits(m_ulLogout, 4);
            tmpClass.addBits(m_ulEmpty, 6);
            m_ulCardIDHeader = (m_ulCardID >> 44);
            tmpClass.addBits(m_ulCardIDHeader, 20);
            tmpClass.addBits(m_ulLibCode, 16);
            tmpClass.addBits(m_ulLibTagType, 4);
            tmpClass.addBits(m_ulCardID - (m_ulCardIDHeader << 44), 44);
            tmpClass.addBits(m_ulRemain, 2);
            return tmpClass.getBytes(byResult);
        } catch (Exception ex) {
            throw new Exception("CReaderEpcCode2 getBytes exception: " + ex.getMessage());
        }
    }

    private static class BitClass {
        private ByteBuffer buffer;

        public BitClass() {
            this.buffer = ByteBuffer.allocate(12);
        }

        public BitClass(byte[] data) {
            this.buffer = ByteBuffer.wrap(data);
        }

        public long getValueUL(int startBit, int length) {
            // This is a simplified placeholder for actual bit manipulation logic
            return 0; // Placeholder
        }

        public void addBits(long value, int length) {
            // This is a simplified placeholder for actual bit manipulation logic
        }

        public int getBytes(byte[] result) {
            byte[] data = buffer.array();
            System.arraycopy(data, 0, result, 0, data.length);
            return data.length;
        }
    }
}


